package com.asset.inventory.viewModel

import android.text.TextUtils
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.asset.inventory.base.BaseApp
import com.asset.inventory.base.BaseViewModel
import com.asset.inventory.kt.logE
import com.asset.inventory.manager.ConfigInfoManager
import com.asset.inventory.model.*
import com.asset.inventory.network.HttpUtils
import com.asset.inventory.network.Request
import com.asset.inventory.network.RequestObserver
import com.asset.inventory.network.RxScheduler
import com.asset.inventory.utils.SpHelper
import com.google.gson.Gson

/**
 *    @author : sibb
 *    date   : 21-3-16
 *    desc   : 登录页面
 */
open class LoginViewModel: BaseViewModel() {

    val userName = ObservableField<String>(SpHelper.getUserName())

    val userPassword = ObservableField<String>(SpHelper.getPassword())

    var isSuccessGetOrgInfo = false

    var isSuccessGetLocationInfo = false

    var token = ""

    private val loginStatus = MutableLiveData<Boolean>()

    private val isShowLoading = MutableLiveData<Boolean>()


    fun loadingLiveData(): MutableLiveData<Boolean> = isShowLoading

    fun observerLoginStatus(): MutableLiveData<Boolean>{
        return loginStatus
    }



    fun login(){
        if(TextUtils.isEmpty(Request.BASE_URL)){
            showToast("请在 Request 文件中配置 BASE_URL")
            return
        }
        if(TextUtils.isEmpty(userName.get()?.trim())){
            showToast("请输入用户名")
            return
        }

        if(TextUtils.isEmpty(userPassword.get()?.trim())){
            showToast("请输入密码")
            return
        }
        isShowLoading.postValue(true)
        val request  = LoginRequest(userName.get(),userPassword.get())
        HttpUtils.instance.login(request).compose(RxScheduler.io_main()).subscribe(object: RequestObserver<Response>{
            override fun onSuccess(t: Response) {
                "登录成功，token -->${t.data}".logE()

                if(t.status == "success"){
                    t.data?.let {
                        token = it
                        loginSuccess()
                        getConfigInfo()
                    }

                }else{
                    isShowLoading.postValue(false)
                    loginStatus.postValue(false)
                }
            }

            override fun onFaile(e: Throwable) {
                "登录失败，token -->${e.message}".logE()
                loginStatus.postValue(false)
                isShowLoading.postValue(false)
                if (BaseApp.instance.isTest){
                    //todo 测试代码
                    token = "qazwer"
                    getConfigInfo()
                }
            }
        })


    }

    fun getConfigInfo(){
        getOrgList()
        getEnableLocationList()
    }

    /**
     * 获取部门人员数据
     */
    fun getOrgList(){
        HttpUtils.instance.getOrgList().compose(RxScheduler.io_main()).subscribe(object: RequestObserver<OrgModel>{
            override fun onSuccess(t: OrgModel) {
                if(t.status == "success"){
                    isSuccessGetOrgInfo = true
                    ConfigInfoManager.saveOrgInfo(t.data)
                    loginSuccess()
                }else{
                    " 获取部门人员数据失败 --> faile".logE()
                    loginStatus.postValue(false)
                    isShowLoading.postValue(false)
                }
            }

            override fun onFaile(e: Throwable) {
                " 获取部门人员数据失败 -->${e.message}".logE()
                isShowLoading.postValue(false)
                loginStatus.postValue(false)
                testGetOrg()
            }
        })
    }

    fun getEnableLocationList(){
        HttpUtils.instance.getEnableLoctionList().compose(RxScheduler.io_main()).subscribe(object: RequestObserver<LocationModel>{
            override fun onSuccess(t: LocationModel) {
                if(t.status == "success"){
                    isSuccessGetLocationInfo = true
                    ConfigInfoManager.saveLocationInfo(t.data)
                    loginSuccess()

                }else{
                    " 获取获取可用位置列表数据失败 --> faile".logE()
                    loginStatus.postValue(false)
                    isShowLoading.postValue(false)
                }
            }

            override fun onFaile(e: Throwable) {
                " 获取获取可用位置列表数据失败 -->${e.message}".logE()
                isShowLoading.postValue(false)
                loginStatus.postValue(false)
                testGetLocalInfo()
            }
        })
    }


    private fun loginSuccess() {
        if (isSuccessGetOrgInfo && isSuccessGetLocationInfo) {
            SpHelper.saveToken(token)
            SpHelper.saveUserName(userName.get()!!)
            SpHelper.savePassword(userPassword.get()!!)
            BaseApp.instance.isOnlineModel = true
            isShowLoading.postValue(false)
            loginStatus.postValue(true)
        }
    }

    fun testGetLocalInfo(){

        val locaStr = "{\n" +
                "    \"status\": \"success\",\n" +
                "    \"data\": [\n" +
                "        {\n" +
                "            \"code\": \"S41\",\n" +
                "            \"name\": \"S41\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"code\": \"YYSJRJA\",\n" +
                "            \"name\": \"运营商接入间A\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"code\": \"YYSJRJB\",\n" +
                "            \"name\": \"运营商接入间B\"\n" +
                "        }\n" +
                "    ]\n" +
                "}"

        val locaData = Gson().fromJson(locaStr,LocationModel::class.java)
        ConfigInfoManager.saveLocationInfo(locaData.data)
        isSuccessGetLocationInfo = true
        loginSuccess()
    }

    fun testGetOrg(){
        val orgStr = "{\n" +
                "    \"status\": \"success\",\n" +
                "    \"data\": [\n" +
                "        {\n" +
                "            \"name\": \"总行-信息技术中心\",\n" +
                "            \"code\": \"kj\",\n" +
                "            \"users\": [\n" +
                "                {\n" +
                "                    \"name\": \"资产管理员-测试\",\n" +
                "                    \"username\": \"kj0005\"\n" +
                "                }\n" +
                "            ]\n" +
                "        },\n" +
                "        {\n" +
                "            \"name\": \"科技管理部\",\n" +
                "            \"code\": \"kj_kjglb\",\n" +
                "            \"users\": [\n" +
                "                {\n" +
                "                    \"name\": \"胡拥军\",\n" +
                "                    \"username\": \"huyongjun\"\n" +
                "                },\n" +
                "                {\n" +
                "                    \"name\": \"赵玉来\",\n" +
                "                    \"username\": \"zhaoyulai\"\n" +
                "                },\n" +
                "                {\n" +
                "                    \"name\": \"遇彩奕\",\n" +
                "                    \"username\": \"yucaiyi\"\n" +
                "                },\n" +
                "                {\n" +
                "                    \"name\": \"王敏\",\n" +
                "                    \"username\": \"wangmin\"\n" +
                "                },\n" +
                "                {\n" +
                "                    \"name\": \"李孟阳\",\n" +
                "                    \"username\": \"ahlimengyang\"\n" +
                "                },\n" +
                "                {\n" +
                "                    \"name\": \"jc1\",\n" +
                "                    \"username\": \"jc1\"\n" +
                "                },\n" +
                "                {\n" +
                "                    \"name\": \"邓楠\",\n" +
                "                    \"username\": \"dengnan\"\n" +
                "                }\n" +
                "            ]\n" +
                "        }\n" +
                "    ]\n" +
                "}"
        val orgData = Gson().fromJson(orgStr,OrgModel::class.java)
        ConfigInfoManager.saveOrgInfo(orgData.data)
        isSuccessGetOrgInfo = true
        loginSuccess()
    }

}